<?php

define('IN',1);
require_once 'common.inc.php';
$allow = array('login','regist','logout');
$act = in_array($_GET['act'],$allow) ? $_GET['act'] : $allow['0'];

## 用户登陆
if ('login' == $act) 
{
    if (POST) 
	{
        $username = trim($_POST['username']);
        $password = md5(trim($_POST['password']));
        $sql = "SELECT * FROM `customer_leader` WHERE `username` = '{$username}'";
        $user = $_ENV['db']->fetch($sql);

		if(!$user)
		{
			$message = '帐户不存在';
		}
        else if ($user['password'] == $password) 
		{
            $fu = cauthcode(json_encode($user),'ENCODE');
            csetcookie('fu',$fu,3600*24*21);
            $_ENV['db']->runSql("UPDATE customer_leader set last_time = ".time().",last_ip = '".ip2long($_SERVER['REMOTE_ADDR'])."'");
            header("Location: index.php",1,302);
            exit;
        } 
		else 
		{
            $message = '密码错误';
        }
        $template->message = $message;
    }
    showMainFrontPage('front/login');
} 
else if('regist' == $act) 
{## 用户注册
    if ($_POST['opt'] == 'getaddress' && AJAX && POST) 
	{
        $data = $_ENV['db']->fetchAll("SELECT * FROM region WHERE `parent_id` = '".(int)$_POST['object_id']."'");
        echo json_encode($data);
        exit();
    }
    if (POST && AJAX) 
	{
        /*验证验证码*/
	   ValiVerifycode();

		/*[数据验证]*/
       $data = ValiData();
	   
        
		$data['state'] = '2';   //前台添加 默认是 未审核
		$data['created_time'] = $_ENV['time'];
		$data['password'] = md5($data['password']);
		$data['source'] = '0';
		$data['enable'] = '0';
	    InsertTable('customer_leader', saddslashes($data));
		
		/*
        $_ENV['db']->runSql("INSERT INTO `customer` ".buildSql(array(
                'username' => $data['username'],
                'password' => md5($data['password']),
                'mobile' => $data['mobile'],
                'email' => $data['email'],
                'created_time' => time()
            )));
        // 获取id
        $insertId = $_ENV['db']->insertId();
        // 发票入库
        $_ENV['db']->runSql("INSERT INTO fapiao ".buildSql(array(
                'uid' => $insertId,
                'name' => $fp['fp_name'],
                'tt' => $fp['fp_tt'],
                'nr' => $fp['tp_nr']
            )));
        // 收货地址入库
        $address['customer_id'] = $insertId;
        $_ENV['db']->runSql("INSERT INTO address ".buildSql($address));
	 */
		
		
		
        outputJson(1,'注册成功');
    } 
	else 
	{
        // 获取地区信息
        $address = $_ENV['db']->fetchAll("SELECT * FROM region WHERE `parent_id` = '0'");
        $template->address = $address;
        $template->addScript('cselector');
        showMainFrontPage('front/regist');
    }
} 
else if('logout' == $act) 
{
    csetcookie('fu',null,-3600);
    header("Location: index.php");
}



/*验证验证码*/
function ValiVerifycode()
{
	
	$verifycode = $_SESSION['verifycode'];
    unset($_SESSION['verifycode']);
    if (md5(strtolower($_POST['captcha'])) != $verifycode) {
   		outputJson(-100,'验证码错误');
    }
}

/*数据验证*/
function ValiData()
{
	$data    = getRequests(array('customer_mark','username','realname','password','tel','address','zip','password_confirm','mobile','email','mark'));
    //$fp      = getRequests(array('fp_name','fp_tt','fp_nr'));
    //$address = getRequests(array('address','tel','zip','receive_name'));
		
	
	# 判断用户名
    if (!preg_match('/[0-9a-zA-Z]/is',$data['username'])) {
    	outputJson(0,'用户名不符合规范，只允许数字和字母');
    }
    $length = strlen($data['username']);
    if ($length < 4 || $length > 10) {
        outputJson(0,'用户名长度错误，必须为4-10位的数字和字母组合');
    }
	if(customerEntity::IsUserExist($data['username']))
	{
		 outputJson(0,'用户名已存在');
	}
		
    # 检查密码
    $length = strlen($data['password']);
    if ($length < 4) {
    	outputJson(0,'为了您的帐户安全，请将密码设置为至少4位字符');
    }
    if ($data['password'] != $data['password_confirm']) {
        outputJson(0,'两次密码输入不一致');
    }
	unset($data['password_confirm']);

     # 检查Email
	 if (strlen($data['email']) > 100) 
	 {
     	outputJson(0,'您的Email地址过长，系统不支持');
     }
	 if(!empty($data['email']) && !CheckEmail($data['email']))
	 {
		 outputJson(0,'Email格式不正确');
	 }
	
	 # 检查手机号
     if (!empty($data['mobile']) && !CheckMobile($data['mobile'])) 
	 {
         outputJson(0,'手机号码格式不正确');
     }


	 if (!empty($data['tel']) && !preg_match('/\d{7}|\d{11}/',$data['tel'])) {
         outputJson(0,'电话号码应为7或11位纯数字，区号和号码间不能有符号');
     }
		
     if (!empty($data['tel']) && (!preg_match('/^\d+$/',$data['zip']) || strlen($data['zip']) != 6)) {
          outputJson(0,'邮编应为6位纯数字');
	 }
		/*
        ##### 检查发票信息
        $length = strlen($fp['fp_name']);
        if ($length < 1 || $length > 100) {
            outputJson(0,'发票名称长度应该为1到10位字符');
        }
        $length = strlen($fp['fp_tt']);
        if ($length < 1 || $length > 100) {
            outputJson(0,'发票抬头长度应该为1到10位字符');
        }
        $length = strlen($fp['fp_nr']);
        if ($length < 1 || $length > 100) {
            outputJson(0,'发票内容长度应该为1到10位字符');
        }
		*/

		/*
        ####### 收货地址信息
        $length = strlen($address['receive_name']);
        if ($length < 1 || $length > 10) {
            outputJson(0,'客户名称长度应该为1到10位字符');
        }
        if (!preg_match('/\d{7}|\d{11}/',$address['tel'])) {
            outputJson(0,'电话号码应为7或11位纯数字，区号和号码间不能有符号');
        }
        if (!preg_match('/^\d+$/',$address['zip']) || strlen($address['zip']) != 6) {
            outputJson(0,'邮编应为6位纯数字');
        }
        if (strlen($address['address']) > 200) {
            outputJson(0,'收货地址不能大于200字节');
        }
		*/
		return $data;
}
